using Microsoft.AspNetCore.Authentication.JwtBearer; // JWT 认证相关功能
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore; // 数据库上下文和查询功能
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.IdentityModel.Tokens; // JWT 令牌验证相关功能
using Microsoft.OpenApi.Models; // Swagger 相关功能
using System.Text; // 字符串编码功能
using UniversalAdmin.Application.Services;
using UniversalAdmin.Domain.Entities;
using UniversalAdmin.Domain.Interfaces;
using UniversalAdmin.Domain.Repositories; // 领域层仓储接口
using UniversalAdmin.Infrastructure.Data.Contexts; // 数据库上下文
using UniversalAdmin.Infrastructure.Repositories; // 基础设施层仓储实现
using UniversalAdmin.Infrastructure.Services; // 基础设施层服务
using UniversalAdmin.Api.Middleware; // 自定义中间件
using UniversalAdmin.Api.Services; // API层服务
using UniversalAdmin.Api.Configurations; // 自定义配置
using UniversalAdmin.Infrastructure.Configurations; // 基础设施层配置

// 创建 WebApplication 构建器
var builder = WebApplication.CreateBuilder(args);

// 配置数据库上下文 - 性能优化
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection"), npgsqlOptions =>
    {
        npgsqlOptions.CommandTimeout(30); // 设置命令超时时间
    });

    // 开发环境配置
    if (builder.Environment.IsDevelopment())
    {
        options.EnableSensitiveDataLogging();
    }
});

// 注册 JwtService
builder.Services.AddScoped<IJwtService, JwtService>();

// 注册 AuthService 登录注册登出
builder.Services.AddScoped<IAuthService, AuthService>();

// 注册 RoleService 角色管理
builder.Services.AddScoped<IRoleService, RoleService>();

// 注册 PermissionService 权限管理
builder.Services.AddScoped<IPermissionService, PermissionService>();

// 注册 UserService 用户管理
builder.Services.AddScoped<IUserService, UserService>();

// 注册 RolePermissionService 角色权限管理
builder.Services.AddScoped<IRolePermissionService, RolePermissionService>();

// 注册 PersonalService 个人资料管理
builder.Services.AddScoped<IPersonalService, PersonalService>();

// 注册 MenuService 菜单管理
builder.Services.AddScoped<IMenuService, MenuService>();

// 注册 SystemConfigService 系统配置管理
builder.Services.AddScoped<ISystemConfigService, SystemConfigService>();

// 注册 OperationLogService 操作日志管理
builder.Services.AddScoped<IOperationLogService, OperationLogService>();

// 注册 ArticleService 文章管理
builder.Services.AddScoped<IArticleService, ArticleService>();

// 注册 ArticleCategoryService 文章分类管理
builder.Services.AddScoped<IArticleCategoryService, ArticleCategoryService>();

// RAG相关服务注册
builder.Services.AddScoped<IChatService, ChatService>();
builder.Services.AddScoped<IDocumentService, DocumentService>();

// 嵌入服务注册 - 使用fallback模式
builder.Services.AddScoped<KimiEmbeddingService>();
builder.Services.AddScoped<MockEmbeddingService>();
builder.Services.AddScoped<IEmbeddingService, FallbackEmbeddingService>();

// 配置文件绑定
builder.Services.Configure<JwtConfig>(builder.Configuration.GetSection("Jwt"));
builder.Services.Configure<KimiConfig>(builder.Configuration.GetSection("Kimi"));
builder.Services.Configure<FileUploadConfig>(builder.Configuration.GetSection("FileUpload"));
builder.Services.Configure<XunfeiConfig>(builder.Configuration.GetSection("Xunfei"));

// 注册HttpClient
builder.Services.AddHttpClient();

// 注册AutoMapper
builder.Services.AddAutoMapper(typeof(UniversalAdmin.Application.Mappings.ApplicationMappingProfile));

// 注册当前用户服务
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<ICurrentUserService, CurrentUserService>();

// 注册 仓储实现类（依赖关系）
builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IMenuRepository, MenuRepository>();
builder.Services.AddScoped<IMenuRoleRepository, MenuRoleRepository>();
builder.Services.AddScoped<ISystemConfigRepository, SystemConfigRepository>();
builder.Services.AddScoped<IOperationLogRepository, OperationLogRepository>();
builder.Services.AddScoped<IArticleRepository, ArticleRepository>();
builder.Services.AddScoped<IArticleCategoryRepository, ArticleCategoryRepository>();

// 角色和权限仓储注册
builder.Services.AddScoped<IRoleRepository, RoleRepository>();
builder.Services.AddScoped<IPermissionRepository, PermissionRepository>();

// RAG相关仓储注册
builder.Services.AddScoped<IDocumentRepository, DocumentRepository>();
builder.Services.AddScoped<IDocumentChunkRepository, DocumentChunkRepository>();
builder.Services.AddScoped<IConversationRepository, ConversationRepository>();
builder.Services.AddScoped<IMessageRepository, MessageRepository>();


// 配置 Identity 服务
builder.Services.AddIdentity<User, Role>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

// 替换默认的 PasswordHasher 为 BCryptPasswordHasher
builder.Services.Replace(
    ServiceDescriptor.Scoped<IPasswordHasher<User>, BCryptPasswordHasher<User>>());

// 配置 JWT 认证（改进版）
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(
            Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!)),
        ValidateIssuer = true,
        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        ValidateAudience = true,
        ValidAudience = builder.Configuration["Jwt:Audience"],
        ValidateLifetime = true,
        ClockSkew = TimeSpan.Zero,
        NameClaimType = System.Security.Claims.ClaimTypes.NameIdentifier
    };

    options.Events = new JwtBearerEvents
    {
        OnMessageReceived = context =>
        {
            var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>();
            var authHeader = context.Request.Headers["Authorization"].FirstOrDefault();
            logger.LogInformation("收到认证请求: {Path}, Authorization头: {AuthHeader}",
                context.Request.Path, authHeader ?? "无");
            return Task.CompletedTask;
        },

        OnTokenValidated = context =>
        {
            var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>();
            var path = context.Request.Path.Value?.ToLower();

            logger.LogInformation("Token验证成功: {Path}", path);
            return Task.CompletedTask;
        },

        OnAuthenticationFailed = async context =>
        {
            var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>();
            logger.LogError("认证失败: {Error}", context.Exception.Message);

            if (context.Exception is SecurityTokenExpiredException)
            {
                context.Response.Headers.Append("Token-Expired", "true");
                logger.LogWarning("Token已过期");
            }
            else if (context.Exception is SecurityTokenInvalidSignatureException)
            {
                logger.LogWarning("Token签名无效");
            }
            else if (context.Exception is SecurityTokenInvalidIssuerException)
            {
                logger.LogWarning("Token发行者无效: {Issuer}", (context.Exception as SecurityTokenInvalidIssuerException)?.InvalidIssuer);
            }
            else if (context.Exception is SecurityTokenInvalidAudienceException)
            {
                logger.LogWarning("Token受众无效: {Audience}", (context.Exception as SecurityTokenInvalidAudienceException)?.InvalidAudience);
            }

            await Task.CompletedTask;
        },

        OnChallenge = context =>
        {
            var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<Program>>();
            logger.LogWarning("认证挑战: {Error}", context.Error ?? "未提供认证信息");
            return Task.CompletedTask;
        }
    };
});

// 其他服务配置

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();

// 配置 Swagger
builder.Services.ConfigureSwagger();

// CORS 配置
builder.Services.AddCors(options =>
    options.AddPolicy("AllowFrontend", policy =>
    {
        policy.WithOrigins("http://localhost:5173",
                            "http://localhost:3000",
                            "http://localhost:8080",
                            "http://localhost:4173",
                            "http://zzaisx.top:5173",
                            "http://admin-hcx.axuege.xyz:5173",
                            "http://admin-zjp.beiweijierui.xyz:5173",
                            "http://admin-yzy.wudkmao.top:5173",
                            "http://47.122.49.186:5173",
                            "http://admin-zjp-two.beiweijierui.xyz:3000",
                            "http://admin-yzy-two.wudkmao.top:3000",
                            "http://admin-hcx-two.axuege.xyz:3000",
                            "http://rag.zzaisx.top:3000"
        )
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials();
    }));

var app = builder.Build();

// 中间件管道配置
app.UseCors("AllowFrontend");

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

// 添加自定义中间件
app.UseMiddleware<UniversalAdmin.Api.Middleware.OperationLogMiddleware>();
app.UseMiddleware<UniversalAdmin.Api.Middleware.PermissionMiddleware>();

app.UseAuthentication();  // 必须在 UseAuthorization 之前
app.UseAuthorization();

app.MapControllers();



app.Run();